package cn.cxy.demo.ui.activity

import android.view.View
import androidx.lifecycle.Observer
import cn.cxy.demo.R
import cn.cxy.demo.base.BaseVmActivity
import cn.cxy.demo.common.loadmore.CommonLoadMoreView
import cn.cxy.demo.common.loadmore.LoadMoreStatus
import cn.cxy.demo.network.response.Article
import cn.cxy.demo.ui.adapter.ArticleAdapter
import cn.cxy.demo.viewmodel.ArticleListViewModel
import kotlinx.android.synthetic.main.activity_article_list.*
import kotlinx.android.synthetic.main.include_reload.*

class ArticleListActivity : BaseVmActivity<ArticleListViewModel>() {
    private lateinit var mAdapter: ArticleAdapter
    override fun viewModelClass() = ArticleListViewModel::class.java
    override fun layoutResId(): Int = R.layout.activity_article_list

    override fun initView() {
        swipeRefreshLayout.run {
            setOnRefreshListener { mViewModel.loadArticleList() }
        }
        mAdapter = ArticleAdapter(R.layout.item_article).apply {
            setLoadMoreView(CommonLoadMoreView())
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener({
                mViewModel.loadMoreArticleList()
            }, recyclerView)
        }
        reloadBtn.setOnClickListener {
            mViewModel.loadArticleList()
        }
    }

    override fun initData() {
        mViewModel.loadArticleList()
    }

    override fun observe() {
        mViewModel.run {
            val context = this@ArticleListActivity
            articleList.observe(context, Observer {
                mAdapter.setNewData(it)
            })
            refreshStatus.observe(context, Observer {
                swipeRefreshLayout.isRefreshing = it
            })
            loadMoreStatus.observe(context, Observer {
                when (it) {
                    LoadMoreStatus.COMPLETED -> mAdapter.loadMoreComplete()
                    LoadMoreStatus.ERROR -> mAdapter.loadMoreFail()
                    LoadMoreStatus.END -> mAdapter.loadMoreEnd()
                    else -> return@Observer
                }
            })
            reloadStatus.observe(context, Observer {
                reloadView.visibility = if (it) View.VISIBLE else View.GONE
            })
        }
    }

    private fun onItemClick(article: Article) {
    }
}
